<template>
  <div
    class="container"
    :style="styleState ? 'background-color: transparent; color: #fff' : 'background-color: #fff'"
  >
    <div class="left">
      <div class="logo" v-if="!styleState" @click="$router.push(`/`)"></div>
      <div class="iconfont icon-bilibili-line logo-icon" v-else @click="$router.push(`/`)"></div>
      <div class="nav-btn">
        <routerLink to="/" href="javascript:;">
          主站
          <span class="iconfont icon-xia down" v-if="!styleState"></span>
        </routerLink>
        <a href="javascript:;">番剧</a>
        <a href="javascript:;">游戏中心</a>
        <a href="javascript:;">直播</a>
        <a href="javascript:;">会员购</a>
        <a href="javascript:;">漫画</a>
        <a href="javascript:;">赛事</a>
        <a href="javascript:;"> <span class="iconfont icon-shouji phone"></span>下载APP</a>
      </div>
    </div>
    <div class="mid">
      <input type="text" class="search" placeholder="嘻嘻哈哈嘻嘻哈" v-model="search" />
      <span class="iconfont icon-sousuo1 search-icon"></span>
    </div>
    <div class="right">
      <div class="personal-btn">
        <ElPopover
          trigger="hover"
          v-if="_isLogin"
          :width="300"
          @show="scla = true"
          @hide="scla = false"
        >
          <template #reference>
            <a
              href="javascript:;"
              class="user-logo login"
              :class="scla && 'scla'"
              :style="`background-image: url(${userBase.face})`"
              @click="
                $router.push({
                  name: 'Personal',
                  query: { hostMid: userBase.mid },
                })
              "
            >
            </a>
          </template>

          <div class="popover-userInfo">
            <div class="nickname">{{ userBase.uname }}</div>
            <div class="level">
              <span>等级{{ userBase.level_info?.current_level }}</span>
              <span class="progress-num">
                {{ userBase.level_info?.current_exp }}/{{ userBase.level_info?.next_exp }}
              </span>
            </div>
            <div class="progress-bar">
              <ElProgress
                :percentage="progressValue"
                :show-text="false"
                :stroke-width="3"
                color="#f3cb85"
              />
            </div>
            <div class="money">
              <div>
                <span class="iconfont icon-Bbi"></span><span>{{ userBase.money }}</span>
              </div>
              <div>
                <span class="iconfont icon-icon-class-b"></span>
                <span>{{ userBase.wallet?.bcoin_balance }}</span>
              </div>
            </div>
            <div class="number">
              <a href="javascript:;">
                <span class="label">关注</span>
                <span class="count">{{ userStart.following }}</span>
              </a>
              <a href="javascript:;">
                <span class="label">粉丝</span>
                <span class="count">{{ userStart.follower }}</span>
              </a>
              <routerLink :to="{ name: '' }" href="javascript:;">
                <span class="label">动态</span>
                <span class="count">{{ userStart.dynamic_count }}</span>
              </routerLink>
            </div>
            <div class="user-nav">
              <div class="link">
                <span class="iconfont icon-geren"></span>
                <span>个人中心</span>
              </div>
              <div class="link">
                <span class="iconfont icon-tougao"></span>
                <span>投稿管理</span>
              </div>
              <div class="link">
                <span class="iconfont icon-qianbao"></span>
                <span>B币钱包</span>
              </div>
              <div class="link">
                <span class="iconfont icon-dingdan"></span>
                <span>订单中心</span>
              </div>
              <div class="link">
                <span class="iconfont icon-zhibo"></span>
                <span>直播中心</span>
              </div>
              <div class="link">
                <span class="iconfont icon-wodekecheng"></span>
                <span>我的课程</span>
              </div>
              <div class="link logout-btn" @click="logout">
                <span class="iconfont icon-tuichu"></span>
                <span>退出</span>
              </div>
            </div>
          </div>
        </ElPopover>
        <a href="javascript:;" v-else class="user-logo logout" @click="openLogin"> 登录 </a>
        <a href="javascript:;">大会员</a>
        <a href="javascript:;">消息</a>
        <a href="javascript:;" @click="routerNeedLogin('Trends')">动态</a>
        <a href="javascript:;" @click="routerNeedLogin('Collection')">收藏</a>
        <a href="javascript:;" @click="routerNeedLogin('History')">历史</a>
        <a href="javascript:;">创作中心</a>
      </div>
      <div class="upload">投稿</div>
    </div>
  </div>

  <ElDialog v-model="visible" title="客户端二维码登录" center width="400px">
    <div class="code-warpper">
      <img src="./image/bv.png" class="top-img" />
      <img src="./image/左护法.png" class="left-img" />
      <img :src="qrCodeUrl" class="code" />
      <img src="./image/右护法.png" class="right-img" />
    </div>
    <div class="tips" style="text-align: center">请使用 哔哩哔哩客户端 扫码登录 或下载APP</div>
    <template #footer>
      <ElButton @click="visible = false"> 取消 </ElButton>
      <ElButton @click="handleLogin" type="primary"> 确认扫码，立即登录 </ElButton>
    </template>
  </ElDialog>
</template>

<script lang="ts">
  import { defineComponent, ref, onMounted, watch } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  // import { ElPopover, ElButton, ElDialog, ElProgress, ElNotification } from 'element-plus'
  // import { useRoute } from 'vue-router'
  import { reqLoginKey, reqLogin, reqUserStart, reqUserBase, reqLogout } from '@/api/user'
  import type { UserStartModel, UserBaseModel } from '@/api/user'
  import QRCode from 'qrcode'
  import { isLogin } from '@/utils/permission'
  import { formatImgUrl } from '@/utils/lib'
  import { useUserStore } from '@/store/moudles/user'

  export default defineComponent({
    name: 'HeaderBar',
  })
</script>

<script lang="ts" setup>
  import { ElNotification } from 'element-plus'

  const route = useRoute()
  let styleState = ref(true)
  watch(
    () => route.name,
    (name) => {
      styleState.value = name === 'Home' || name === 'History' ? true : false
    },
  )

  const _isLogin = ref(false)
  // const route = useRoute()
  onMounted(() => {
    if (isLogin()) {
      _isLogin.value = true
      getUserBase()
      getUserStart()
    }
  })

  const search = ref('')

  //* -----------------登录逻辑---------------------

  const qrCodeUrl = ref('')
  let _oauthKey = ''
  const visible = ref(false)

  const openLogin = async () => {
    visible.value = true
    const { url, oauthKey } = await reqLoginKey()
    _oauthKey = oauthKey
    qrCodeUrl.value = await QRCode.toDataURL(url)
  }

  const handleLogin = async () => {
    try {
      const { sid } = await reqLogin(_oauthKey)
      _isLogin.value = true
      localStorage.setItem('sid', sid)
      ElNotification({
        title: '登录成功！',
        type: 'success',
      })
      visible.value = false
      window.location.reload()
    } catch (err) {
      ElNotification({
        title: '请确认扫码后再点击登录哟',
        type: 'error',
        duration: 3000,
      })
    }
  }

  //* ---------------登录后逻辑--------------------------
  const UserStore = useUserStore()
  const scla = ref(false)
  const userBase = ref<Partial<UserBaseModel>>({})
  const userStart = ref<Partial<UserStartModel>>({})
  const progressValue = ref(0)

  async function getUserBase() {
    const res = await reqUserBase()

    res.face = formatImgUrl(res.face)
    UserStore.setUserName_Face(res.uname, res.face, res.mid)

    typeof res.level_info.next_exp === 'string'
      ? (progressValue.value = 100)
      : (progressValue.value = (res.level_info.current_exp / res.level_info.next_exp) * 100)

    userBase.value = res
  }

  async function getUserStart() {
    const res = await reqUserStart()
    userStart.value = res
    UserStore.setUserCount(res.dynamic_count, res.follower, res.following)
  }

  const logout = () => {
    reqLogout()
    localStorage.removeItem('sid')
    window.location.reload()
  }

  const router = useRouter()
  const routerNeedLogin = (routeName: string) => {
    if (!_isLogin.value) {
      ElNotification({
        title: '请先登录~',
        type: 'error',
        duration: 3000,
      })
      openLogin()
    } else {
      if (routeName === 'Collection') {
        router.push({ name: routeName, query: { hostMid: userBase.value.mid } })
        return
      }
      router.push({ name: routeName })
    }
  }
</script>

<style scoped>
  @import url('//at.alicdn.com/t/font_2974912_0g7sde8pnmga.css');
</style>

<style lang="less" scoped>
  .container {
    position: absolute;
    top: 0;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px;
    height: 56px;
    min-width: 1200px;

    box-sizing: border-box;
    background-color: #fff;
    box-shadow: 0 0px 6px #00000040;
  }

  .left {
    display: flex;
    align-items: center;
    height: 100%;
    width: 520px;
    .logo {
      width: 100px;
      height: 100%;
      background-image: url('./image/logo.png');
      background-position: center center;
      background-repeat: no-repeat;
      background-size: contain;
      transform: scale(1.25);
      cursor: pointer;

      // margin-right: 10px;
    }

    .logo-icon {
      font-size: 20px;
      padding-left: 20px;
      padding-right: 5px;
      cursor: pointer;

      // font-weight: bold;
    }
    .nav-btn {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 420px;

      a {
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 14.5px;

        .down {
          font-size: 12px;
        }

        .phone {
          font-size: 20px;
          color: #00a1d6;
        }
      }
    }
  }

  .mid {
    width: 450px;
    height: 100%;
    margin: 0 10px;
    display: flex;

    .search {
      display: block;
      width: 380px;
      height: 100%;
      padding: 8px 15px;
      box-sizing: border-box;
      background-color: #f4f4f4;
      outline: none;
      border: 1px solid #e7e7e7;
      transition: color 300ms;
      color: #999;
      &:focus {
        color: #222;
      }
    }
    .search-icon {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 40px;
      height: 100%;
      background-color: #e7e7e7;
      color: #505050;
      cursor: pointer;
      // font-weight: bold;
    }
  }

  .right {
    display: flex;
    align-items: center;
    width: 470px;
    height: 100%;

    .personal-btn {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-right: 5px;
      width: 330px;
      a {
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 14.5px;
      }

      .user-logo {
        margin-right: 10px;
        width: 40px;
        height: 40px;
        border-radius: 50%;
        flex-shrink: 0;
        box-sizing: border-box;

        &.login {
          // background-image: url('./image/userlogo.webp');
          background-repeat: no-repeat;
          background-position: center center;
          background-size: contain;
          transition: transform 300ms;
          z-index: 9999999999;

          &.scla {
            transform: scale(1.7) translateY(30%);
          }
        }

        &.logout {
          font-size: 14px;
          font-weight: bold;
          text-align: center;
          border: 1px solid #fb7299;
          color: skyblue;
        }
      }
    }
    .upload {
      display: flex;
      justify-content: center;
      align-items: center;
      margin: 0 6px;
      height: 100%;
      width: 100px;
      background-color: #fb7299;
      color: #fff;
      border-radius: 3px;
      font-size: 15px;
      cursor: pointer;
    }
  }

  .code-warpper {
    padding: 30px 20px;
    display: flex;
    // align-items: center;
    justify-content: center;
    text-align: center;

    position: relative;

    .top-img {
      position: absolute;
      top: 0px;
      height: 40px;
    }

    .left-img {
      height: 100px;
    }

    .right-img {
      height: 100px;
    }

    .code {
      // border: 1px solid red;
      width: 170px;
      height: 170px;
    }
  }

  .popover-userInfo {
    width: 300px;
    color: #212121;

    .nickname {
      padding: 20px 0;
      text-align: center;
      font-size: 16px;
      font-weight: bold;
    }

    .level {
      display: flex;
      justify-content: space-between;
      padding: 0 15px;
      padding-bottom: 10px;

      .progress-num {
        color: #aaa;
        font-size: 12px;
      }
    }
    .progress-bar {
      padding: 0 15px;
    }

    .money {
      display: flex;
      align-items: center;
      padding: 10px 0;
      padding-left: 15px;
      div {
        display: flex;
        align-items: center;
        margin-right: 15px;

        .iconfont {
          width: 35px;
          font-size: 24px;
        }
        .icon-Bbi {
          color: skyblue;
        }

        .icon-icon-class-b {
          color: #ffae00;
        }
      }
    }

    .number {
      display: flex;
      align-items: center;
      justify-content: space-around;
      padding: 10px 0;
      border-top: 1px solid #eee;
      border-bottom: 1px solid #eee;

      a {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        width: 60px;

        .label {
          font-size: 12px;
          color: #aaa;
        }

        .count {
          font-size: 15px;
          font-weight: bold;
        }
      }
    }

    .user-nav {
      .link {
        padding-left: 15px;
        display: flex;
        align-items: center;
        height: 40px;
        font-size: 15px;
        cursor: pointer;
        transition: background-color 200ms;
        &:hover {
          background-color: #00000008;
        }
        .iconfont {
          margin-right: 10px;
          font-size: 22px;
          color: #979797;
        }
      }
      .logout-btn {
        &:hover {
          background-color: transparent;
        }
        padding-top: 10px;
        height: 30px;
        border-top: 1px solid #eee;
      }
    }
  }
</style>
